package com.itic.mall.mobile.share;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.itic.appbase.framework.common.constants.DBConst;
import com.itic.appbase.framework.type.DefaultSysSettingKeyValue;
import com.itic.appbase.framework.type.UserShareType;
import com.itic.appbase.framework.utils.IdGen;
import com.itic.appbase.framework.utils.StringHelper;
import com.itic.appbase.framework.utils.ValueHelper;
import com.itic.mall.mobile.base.BaseMobileInterface;
import com.itic.mall.system.goods.goodsspu.persistence.model.GoodsSpu;
import com.itic.mall.system.goods.goodsspu.persistence.model.GoodsSpuExample;
import com.itic.mall.system.goods.goodsspu.persistence.model.GoodsSpuExample.Criteria;
import com.itic.mall.system.goods.goodsspu.persistence.vo.ConEmptyVo;
import com.itic.mall.system.goods.goodsspu.service.GoodsSpuService;
import com.itic.mall.system.share.sharehistory.persistence.model.ShareHistory;
import com.itic.mall.system.share.sharehistory.service.ShareHistoryService;
import com.itic.mall.system.users.shareLog.service.UsersShareLogService;
import com.itic.mall.system.users.usersmall.persistence.model.UsersMall;

import cn.jpush.api.report.UsersResult.User;

/**
 * 京东接口
 * 
 * @author 王文鑫
 * @date 2017年12月22日 上午10:33:24
 */
@Controller
@RequestMapping(value = "/mobile/share")
public class ShareInterface extends BaseMobileInterface {

	@Autowired
	private ShareHistoryService shareHistoryService;
	@Autowired
	private GoodsSpuService goodsSpuService;
	@Autowired
	private UsersShareLogService usersShareLogService;
	
   /**
	 * 分享单个商品
	 * @author 许小宝
	 * @date 2017年12月22日 下午3:31:52
	 * @param request
	 * @param response
	 * @param address
	 * @return
	 */
	@RequestMapping(value = "/single")
	@ResponseBody
	public Map<String, Object> single( HttpServletRequest request, HttpServletResponse response,String spuId,String token,String appId ) {
		Map<String, Object> resultMap = new HashMap<String, Object>();

		String errorCode = PARAM_ERROR_CODE; // 缺少必填参数
		String errorMsg = PARAM_ERROR_MSG;// 缺少必填参数，返回信息
		try {
			if( StringHelper.isNotBlank(token) && StringHelper.isNotBlank(appId) && StringHelper.isNotBlank(spuId) ){
				UsersMall user = getUsersByTokenAndAppId(token, appId);
				if( null != user ){
					
					GoodsSpu goodsSpu = goodsSpuService.get(spuId);
					
					if( null != goodsSpu ){
						//添加分享统计
	  					addShare(goodsSpu);
	  					
						Map<String, Object> dataMap = new HashMap<String, Object>();
						
						String shareUrl = getShareUrl(goodsSpu,user);
						
						String type = "友惠";
						if( "jd".equals(goodsSpu.getSpuPlatform()) ){
							type="京东";
						}else if( "tm".equals(goodsSpu.getSpuPlatform()) ){
							type="天猫";
						}else if( "tb".equals(goodsSpu.getSpuPlatform()) ){
							type="淘宝";
						}
						
						//图文分享
    					ImgwordVo imgword = new ImgwordVo();
    					imgword.setImage(goodsSpu.getMainImageUrl());
    					
    					StringBuffer sb = new StringBuffer();
    					sb.append(goodsSpu.getGoodsName()+"\n");
    					sb.append("----------------------\n");
    					sb.append( type+"价："  );
    					sb.append(goodsSpu.getPrice());
    					sb.append("元\n");
    					sb.append( "券后价：");
    					sb.append(goodsSpu.getConPrice());
    					sb.append("元\n");
    					sb.append("----------------------\n");
    					sb.append(shareUrl);
    					imgword.setWord(sb.toString());
    					
						dataMap.put("imgword", imgword);//图文
						
						dataMap.put("poster", getPoster(goodsSpu,user));//海报
						//链接分享
						LinkVo urlVo = new LinkVo();
						urlVo.setImgUrl(goodsSpu.getMainImageUrl());
						urlVo.setTitle("【领券更便宜】"+goodsSpu.getGoodsName());
						urlVo.setContent("原价"+goodsSpu.getPrice()+"元,券后价"+goodsSpu.getConPrice()+"元,"+type+"商城，正品保证。" );
						urlVo.setUrl(shareUrl);
						
						dataMap.put("link", urlVo);//链接
						
						dataMap.put("preMoney", goodsSpu.getWlCommission()==null?"0":goodsSpu.getWlCommission());//商品佣金
						//添加用户分享记录
						this.usersShareLogService.addShareLog(UserShareType.Good, goodsSpu.getId(), user);
						resultMap.put(DATA, dataMap);
						errorCode = SUCCESS_ERROR_CODE;
						errorMsg = SUCCESS_ERROR_MSG;
						
					}else{
						errorCode = GOODS_NOT_FIND_ERROR_CODE;
						errorMsg = GOODS_NOT_FIND_ERROR_MSG;
					}
				}else{
					errorCode = LOGIN_ERROR_CODE;
					errorMsg = LOGIN_ERROR_MSG;
				}
			}
			
		} catch (Exception e) {
			// 服务器异常处理
			errorCode = SERVER_ERROR_CODE;
			errorMsg = SERVER_ERROR_MSG;
			// 打印异常日志
			logException("ShareInterface", "single", e.toString(), "单品分享", e);
		}
		resultMap.put(CODE, errorCode);
		resultMap.put(MSG, errorMsg);
		isCrrossDomain(response); // 跨域处理
		return resultMap;
	}
	

	/**
	 * 分享多个商品
	 * 
	 * @author 许小宝
	 * @date 2017年12月22日 下午3:31:52
	 * @param request
	 * @param response
	 * @param address
	 * @return
	 */
	@RequestMapping(value = "/batch")
	@ResponseBody
	public Map<String, Object> batch( HttpServletRequest request, HttpServletResponse response,String spuIds,String token,String appId ) {
		Map<String, Object> resultMap = new HashMap<String, Object>();

		String errorCode = PARAM_ERROR_CODE; // 缺少必填参数
		String errorMsg = PARAM_ERROR_MSG;// 缺少必填参数，返回信息
		try {
			if( StringHelper.isNotBlank(token) && StringHelper.isNotBlank(appId) && StringHelper.isNotBlank(spuIds) ){
				UsersMall user = getUsersByTokenAndAppId(token, appId);
				if( null != user ){
					
					String[] split = spuIds.split(",");
					int length = split.length;
					if( length <= 9 ){
						Map<String, Object> dataMap = new HashMap<String, Object>();
						List<String> posters = new ArrayList<String>();//存放海报的图片路径
						int fails = 0;
						for( int i=0; i<split.length; i++ ){
						    GoodsSpu spu = goodsSpuService.get(split[i]);
						    if( null != spu ){
						    	//添加分享统计
			  					addShare(spu);
						    	posters.add(getPoster(spu, user));
						    	//this.usersShareLogService.addShareLog(UserShareType.Good, spu.getId(), user);
						    }else{
						        fails++;
						    }
						}
						//商品下架的提醒消息
						if( fails>0 ){
							dataMap.put("failure", "有"+fails + "件商品已下架了");
						}else{
							dataMap.put("failure", "");
						}
						dataMap.put("poster", posters);
						resultMap.put(DATA, dataMap );
						errorCode = SUCCESS_ERROR_CODE;
						errorMsg = SUCCESS_ERROR_MSG;
					}else{
						errorCode = MAX_NINE_ERROR_CODE;
						errorMsg = MAX_NINE_ERROR_MSG;
					}
				}else{
					errorCode = LOGIN_ERROR_CODE;
					errorMsg = LOGIN_ERROR_MSG;
				}
			}
			
		} catch (Exception e) {
			// 服务器异常处理
			errorCode = SERVER_ERROR_CODE;
			errorMsg = SERVER_ERROR_MSG;
			// 打印异常日志
			logException("ShareInterface", "batch", e.toString(), "批量分享", e);
		}
		resultMap.put(CODE, errorCode);
		resultMap.put(MSG, errorMsg);
		isCrrossDomain(response); // 跨域处理
		return resultMap;
	}
	
	
	/**
	 * 分享多个商品
	 * 
	 * @author 许小宝
	 * @date 2017年12月22日 下午3:31:52
	 * @param request
	 * @param response
	 * @param address
	 * @return
	 */
	@RequestMapping(value = "/store")
	@ResponseBody
	public Map<String, Object> store( HttpServletRequest request, HttpServletResponse response,String token,String appId ) {
		Map<String, Object> resultMap = new HashMap<String, Object>();

		String errorCode = PARAM_ERROR_CODE; // 缺少必填参数
		String errorMsg = PARAM_ERROR_MSG;// 缺少必填参数，返回信息
		try {
			if( StringHelper.isNotBlank(token) && StringHelper.isNotBlank(appId) ){
				UsersMall user = getUsersByTokenAndAppId(token, appId);
				if( null != user ){
					if( "002".equals(user.getType()) ){
						Map<String, Object> dataMap = new HashMap<String, Object>();
						//链接分享
						LinkVo urlVo = new LinkVo();
						urlVo.setImgUrl("http://file.jhjvip.cn/yhjlogo.png");
						urlVo.setTitle(user.getUserNickName());
						urlVo.setContent( "你的好友"+user.getUserNickName()+"邀请你观赏Ta的友惠家店铺，快快查看~~" );
						String defaultValue = DefaultSysSettingKeyValue.shareYunStoreLink.getValue();
						String sysKey = sysSettingService.getByKey(DefaultSysSettingKeyValue.shareYunStoreLink.getValue());
						if( StringHelper.isNotBlank(sysKey) ){
							defaultValue = sysKey;
						}
						urlVo.setUrl(defaultValue+user.getId());
						
						dataMap.put("link", urlVo);//链接
						dataMap.put("poster", getStorePoster(user));
						
						resultMap.put(DATA, dataMap);
						errorCode = SUCCESS_ERROR_CODE;
						errorMsg = SUCCESS_ERROR_MSG;
					}else{
						errorCode = NOT_YUNED_ERROR_CODE;
						errorMsg = NOT_YUNED_ERROR_MSG;
					}
				}else{
					errorCode = LOGIN_ERROR_CODE;
					errorMsg = LOGIN_ERROR_MSG;
				}
			}
			
		} catch (Exception e) {
			// 服务器异常处理
			errorCode = SERVER_ERROR_CODE;
			errorMsg = SERVER_ERROR_MSG;
			// 打印异常日志
			logException("ShareInterface", "batch", e.toString(), "批量分享", e);
		}
		resultMap.put(CODE, errorCode);
		resultMap.put(MSG, errorMsg);
		isCrrossDomain(response); // 跨域处理
		return resultMap;
	}
	
	
	
	private Object getStorePoster(UsersMall user) {
		return "http://file.jhjvip.cn/images/welcome.jpg";
	}
	
	/**
	 * 优惠券为空时返回的信息
	 * @author 许小宝
	 * @date 2017年12月22日 下午3:31:52
	 * @param request
	 * @param response
	 * @param address
	 * @return
	 */
	@RequestMapping(value = "/spuConEmpty")
	@ResponseBody
	public Map<String, Object> spuConEmpty( HttpServletRequest request, HttpServletResponse response,String id ) {
		Map<String, Object> resultMap = new HashMap<String, Object>();

		String errorCode = PARAM_ERROR_CODE; // 缺少必填参数
		String errorMsg = PARAM_ERROR_MSG;// 缺少必填参数，返回信息
		try {
			if( StringHelper.isNotBlank(id) ){
				Map<String, Object> dataMap = new HashMap<String, Object>();
				ShareHistory shareHistory = shareHistoryService.get(id);
				if( null != shareHistory ){
					String spuId = shareHistory.getSpuId();
					GoodsSpu goodsSpu = goodsSpuService.get(spuId);
					if( null != goodsSpu ){
						ConEmptyVo emptyVo = new ConEmptyVo();
						emptyVo.setSpuId(spuId);
						emptyVo.setGoodsName(goodsSpu.getGoodsName());
						emptyVo.setMainImageUrl(goodsSpu.getMainImageUrl());
						emptyVo.setPrice(goodsSpu.getPrice());
						emptyVo.setConPrice(goodsSpu.getConPrice());
						dataMap.put("emptySpu", emptyVo);
						//更新商品信息为没有优惠券
						goodsSpu.setConPrice(goodsSpu.getPrice());
						goodsSpu.setCouponMoney(0.00);
						goodsSpuService.edit(goodsSpu);
					}
					
					GoodsSpuExample example = new GoodsSpuExample();
					Criteria criteria = example.createCriteria();
					criteria.andIsEffectiveEqualTo(DBConst.TRUE);// 是否有效
					criteria.andIsShowEqualTo(DBConst.TRUE);// 是否可见
					criteria.andIsJingpingEqualTo(DBConst.TRUE);
					this.handlePageQueryDefault(request, example);// 分页
					int count = goodsSpuService.count(example);// 总条数
					List<GoodsSpu> list = goodsSpuService.list(example);// 数据list
					
					dataMap.put("total", count);
					dataMap.put("isMore", isMore(request, count));
					dataMap.put("list", ValueHelper.tranList2MapList(list,spuIgnoreProperties));
					
					resultMap.put(DATA, dataMap);
					errorCode = SUCCESS_ERROR_CODE; // 缺少必填参数
					errorMsg = SUCCESS_ERROR_CODE;// 缺少必填参数，返回信息
				}else{
					errorCode = LINK_NULL_ERROR_CODE;
					errorMsg = LINK_NULL_ERROR_MSG;
				}
			}
		} catch (Exception e) {
			// 服务器异常处理
			errorCode = SERVER_ERROR_CODE;
			errorMsg = SERVER_ERROR_MSG;
			// 打印异常日志
			logException("ShareInterface", "spuConEmpty", e.toString(), "优惠券为空", e);
		}
		resultMap.put(CODE, errorCode);
		resultMap.put(MSG, errorMsg);
		isCrrossDomain(response); // 跨域处理
		return resultMap;
	}
	
	/**
	 * 获取优惠券的链接URL
	 * @author 许小宝
	 * @date 2017年12月22日 下午3:31:52
	 * @param request
	 * @param response
	 * @param address
	 * @return
	 */
	@RequestMapping(value = "/getConLink")
	@ResponseBody
	public Map<String, Object> getConLink( HttpServletRequest request, HttpServletResponse response,String id ) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		String errorCode = PARAM_ERROR_CODE; // 缺少必填参数
		String errorMsg = PARAM_ERROR_MSG;// 缺少必填参数，返回信息
		try {
			if( StringHelper.isNotBlank(id) ){
				ShareHistory shareHistory = shareHistoryService.get(id);
				if( null != shareHistory ){
					if( "coupon".equals(shareHistory.getLinkType()) ){
						//还是要实时的获取京东的优惠券信息
						String link = "";
						if( StringHelper.isNotBlank(shareHistory.getConUrl()) ){
							link = shareHistory.getConUrl();
							errorCode = SUCCESS_ERROR_CODE;
							errorMsg = SUCCESS_ERROR_MSG;
						}else{
							//生成优惠券的二合一链接，更新数据库
							//判断是否为京东商品
							String tempLink = goodsSpuService.getConErheyiLink(shareHistory.getSpuId(),shareHistory.getUserId());
							if( StringHelper.isNotBlank(tempLink) ){
								link = tempLink;
								shareHistory.setConUrl(link);
								shareHistoryService.edit(shareHistory);
								errorCode = SUCCESS_ERROR_CODE;
								errorMsg = SUCCESS_ERROR_MSG;
							}else{
								errorCode = CONPRICE_NULL_ERROR_CODE;
								errorMsg = CONPRICE_NULL_ERROR_MSG;
							}
						}
						resultMap.put(DATA, link);
						resultMap.put("spuId", shareHistory.getSpuId());
					}else{
						//还是要实时的获取京东的优惠券信息
						String link = "";
						if( StringHelper.isNotBlank(shareHistory.getCommonUrl()) ){
							link = shareHistory.getCommonUrl();
							errorCode = SUCCESS_ERROR_CODE;
							errorMsg = SUCCESS_ERROR_MSG;
						}else{
							//生成二合一链接，更新数据库
							//生成优惠券的二合一链接，更新数据库
							String tempLink = goodsSpuService.getCommonErheyiLink(shareHistory.getSpuId(),shareHistory.getUserId());
							if( StringHelper.isNotBlank(tempLink) ){
								link = tempLink;
								shareHistory.setCommonUrl(link);
								shareHistoryService.edit(shareHistory);
								errorCode = SUCCESS_ERROR_CODE;
								errorMsg = SUCCESS_ERROR_MSG;
							}else{
								//该商品已经下架了
								shareHistoryService.delete(shareHistory);
								goodsSpuService.deleteById(shareHistory.getSpuId());
								errorCode = LINK_NULL_ERROR_CODE;
								errorMsg = LINK_NULL_ERROR_MSG;
							}
						}
						resultMap.put(DATA, link);
						resultMap.put("spuId", shareHistory.getSpuId());
					}
				}else{
					errorCode = LINK_NULL_ERROR_CODE;
					errorMsg = LINK_NULL_ERROR_MSG;
				}
			}
		} catch (Exception e) {
			// 服务器异常处理
			errorCode = SERVER_ERROR_CODE;
			errorMsg = SERVER_ERROR_MSG;
			// 打印异常日志
			logException("ShareInterface", "getConLink", e.toString(), "获取优惠券的链接URL", e);
		}
		resultMap.put(CODE, errorCode);
		resultMap.put(MSG, errorMsg);
		isCrrossDomain(response); // 跨域处理
		return resultMap;
	}
	
	/**
	 * 获取优惠券的链接URL
	 * @author 许小宝
	 * @date 2017年12月22日 下午3:31:52
	 * @param request
	 * @param response
	 * @param address
	 * @return
	 */
	@RequestMapping(value = "/getCommonLink")
	@ResponseBody
	public Map<String, Object> getCommonLink( HttpServletRequest request, HttpServletResponse response,String id ) {
		Map<String, Object> resultMap = new HashMap<String, Object>();

		String errorCode = PARAM_ERROR_CODE; // 缺少必填参数
		String errorMsg = PARAM_ERROR_MSG;// 缺少必填参数，返回信息
		try {
			if( StringHelper.isNotBlank(id) ){
				ShareHistory shareHistory = shareHistoryService.get(id);
				if( null != shareHistory ){
					//还是要实时的获取京东的优惠券信息
					String link = "";
					if( StringHelper.isNotBlank(shareHistory.getCommonUrl()) ){
						link = shareHistory.getCommonUrl();
						errorCode = SUCCESS_ERROR_CODE;
						errorMsg = SUCCESS_ERROR_MSG;
					}else{
						//生成二合一链接，更新数据库
						//生成优惠券的二合一链接，更新数据库
						String tempLink = goodsSpuService.getCommonErheyiLink(shareHistory.getSpuId(),shareHistory.getUserId());
						if( StringHelper.isNotBlank(tempLink) ){
							link = tempLink;
							shareHistory.setCommonUrl(link);
							shareHistoryService.edit(shareHistory);
							errorCode = SUCCESS_ERROR_CODE;
							errorMsg = SUCCESS_ERROR_MSG;
						}else{
							//该商品已经下架了
							//该商品已经下架了
							shareHistoryService.delete(shareHistory);
							goodsSpuService.deleteById(shareHistory.getSpuId());
							errorCode = LINK_NULL_ERROR_CODE;
							errorMsg = LINK_NULL_ERROR_MSG;
						}
					}
					resultMap.put(DATA, link);
				}else{
					errorCode = LINK_NULL_ERROR_CODE;
					errorMsg = LINK_NULL_ERROR_MSG;
				}
			}
		} catch (Exception e) {
			// 服务器异常处理
			errorCode = SERVER_ERROR_CODE;
			errorMsg = SERVER_ERROR_MSG;
			// 打印异常日志
			logException("ShareInterface", "getConLink", e.toString(), "获取优惠券的链接URL", e);
		}
		resultMap.put(CODE, errorCode);
		resultMap.put(MSG, errorMsg);
		isCrrossDomain(response); // 跨域处理
		return resultMap;
	}
	
	/**
	 * 添加分享历史信息记录
	 * @param goodsSpu
	 * @param user
	 * @return
	 */
	private String getShareUrl(GoodsSpu goodsSpu, UsersMall user) {
		String result = DefaultSysSettingKeyValue.shareLoadingLink.getValue();
		
		String byKey = sysSettingService.getByKey(DefaultSysSettingKeyValue.shareLoadingLink.getKey());
		if( StringHelper.isNotBlank(byKey) ){
			result = byKey;
		}
		
	    //二合一转链接,如果优惠券没有成功转链接，就返回空,如果不是优惠券商品，则正常链接
		List<ShareHistory> list = shareHistoryService.listBySpuIdAndUserId( goodsSpu.getId(), user.getId() );
		if( list.size()>0 ){
			result += list.get(0).getId();
		}else{
			//创建一条数据库
			String newId = IdGen.uuid();
			result += newId;
			ShareHistory shareHistory = new ShareHistory();
			shareHistory.setId(newId);
			shareHistory.setReorder(0);
			shareHistory.setUserId(user.getId());
			shareHistory.setSpuId(goodsSpu.getId());
			if( goodsSpu.getCouponMoney()>0 ){
				shareHistory.setLinkType("coupon");
			}else{
				shareHistory.setLinkType("common");
			}
			shareHistoryService.add(shareHistory);
		}
		return result;
	}
	
	
	
}
